package cn.hls.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.hls.dao.AreaDao;
import cn.hls.entity.Area;
import cn.hls.entity.Org;
import cn.hls.entity.vo.ExtTree;
import cn.hls.entity.vo.PageInfo;
import cn.hls.exception.BussinessException;
import cn.hlsconstant.DataAssessEnum;

@Component("areaDao")
public class AreaDaoImpl extends BaseDaoImpl<Area> implements AreaDao {

	
	public Area findArea(Area entity)throws Exception{
		StringBuilder hql = new StringBuilder("from Area m where (m.name = ? or m.code=?) and  deleted=?  " );
		List<Object> params=new ArrayList<Object>();
		params.add(entity.getName().trim());
		params.add(entity.getCode().trim());
		params.add(false);
		if(entity.getParent()!=null&&	entity.getParent().getId()!=null){
			hql.append("and m.parent.id=? ");
			params.add(entity.getParent().getId());
		}
		Query query = getSession().createQuery(hql.toString());
		for(int i=0;i<params.size();i++){
			query.setParameter(i, params.get(i));
		}
		Area area = (Area) query.uniqueResult();
		return area;
	}
	
	
	@Override
	public String delete(Long id) throws Exception {
		try {
			Area area =  find(id);
			if (checkChildren(id)) {
				return "[" + area.getName() + "] 存在有子组织,不允许删除！";
			}
			super.delete(id);
			return "ok";
		} catch (Exception e) {
			throw new BussinessException(DataAssessEnum.DELETE_ERROR, "组织数据删除失败");
		}
	}
	
	/**
	 * 根据编号查询模块是否存在子模块信息
	 * 
	 * @param id编号
	 * @return boolean
	 */
	private boolean checkChildren(Long id) throws Exception {
		String hql = "select count(id) from Area where parent.id=? and deleted=? ";
		return ((Long) getSession().createQuery(hql).setParameter(0, id).setParameter(1, false).uniqueResult()).longValue() > 0L;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ExtTree> loadChildAreaInfo(Area entity, Object nodeId) throws Exception {
		StringBuilder selectHql = new StringBuilder();
		List<Object> paramList = new ArrayList<Object>();
		selectHql.append("select new cn.hls.entity.vo.ExtTree(f.name ,f.id,f.code,(select case when count(id) = 0 then true else false end from Area  where deleted=false and parent.id=f.id) as leaf) from Area f where deleted=?  ");
		paramList.add(false);
		if (nodeId == null)
			selectHql.append(" and parent.id is null");
		else {
			if ((Long) nodeId != 0L) {
				selectHql.append(" and parent.id=?");
				paramList.add(nodeId);
			}
		}
		if ((entity != null) && (StringUtils.hasText(entity.getName()))) {
			selectHql.append(" and name like ?");
			paramList.add("%" + entity.getName() + "%");
		}
		selectHql.append(" order by sort");
		return (List<ExtTree>) find(selectHql.toString(), paramList.toArray());
	}
	 
	@Override
	public PageInfo<Area> loadAreaInfo(PageInfo<Area> page, Area entity)
			throws Exception {
		// 定义查询Hql语句
		StringBuilder selectHql = new StringBuilder();
		// 定义汇总Hql语句
		StringBuilder counthql = new StringBuilder();
		// 定义查询参数
		List<Object> paramList = new ArrayList<Object>();
		selectHql.append("from Area where  deleted=? ");
		paramList.add(false);
		if (entity != null) {
			Long fatherId = entity.getId();
			if (fatherId == null || fatherId == 0)
				selectHql.append(" and  parent.id is null ");
			else {
				selectHql.append(" and  parent.id=?");
				paramList.add(fatherId);
			}
			if (StringUtils.hasText(entity.getName())) {
				selectHql.append(" and name like ?");
				paramList.add("%" + entity.getName().trim() + "%");
			}
		}
		counthql.append(" select count(id) ").append(selectHql);
		selectHql.append(" order by sort");
		return find(selectHql.toString(), counthql.toString(), paramList.toArray(), page);
	}

	@Override
	public List<Area> loadAreaList(Area entity) throws Exception {
		// 定义查询Hql语句
			StringBuilder selectHql = new StringBuilder();
			// 定义查询参数
			List<Object> paramList = new ArrayList<Object>();
			selectHql.append("from Area where  deleted=? ");
			paramList.add(false);
			if (entity != null) {
				Long fatherId = entity.getId();
				if (fatherId == null || fatherId == 0)
					selectHql.append(" and  parent.id is null ");
				else {
					selectHql.append(" and  parent.id=?");
					paramList.add(fatherId);
				}
				if (StringUtils.hasText(entity.getName())) {
					selectHql.append(" and name like ?");
					paramList.add("%" + entity.getName().trim() + "%");
				}
			}
			selectHql.append(" order by sort");
			return findByHql(selectHql.toString(),   paramList.toArray());
	}


	@Override
	public void updateSort(String ids) throws Exception {
		String[] tempIds = ids.split(",");
		for (int i = 0; i < tempIds.length; i++) {
			String hql = "update Area set sort=? where id=?";
			executeHQLUpdate(hql, new Object[] { i + 1, Long.valueOf(tempIds[i]) });
		}
		
	}


}
